<?php
/**
* @software         [JiJinCMS]
* @author           [上海集锦信息科技有限公司]
* @website          [http://www.jijinweb.com]
* @email            [sunny@jijinweb.com]
**/
namespace app\admin\controller;
use think\facade\View;
use think\facade\Db;
use think\facade\Request;
class TableField extends \app\admin\controller\Admin{
    public function __construct(\think\App $app) {
        parent::__construct($app);
        $this->model=new \app\admin\model\TableFieldModel();
        $this->validate=new \app\admin\validate\TableFieldValidate();
        //字段类型        
        $this->fieldtype_inc=array(
           "varchar"=>              "字符型0-255字节(varchar)",
           "char"=>                 "定长字符型0-255字节(char)",
           "text"=>                 "小型字符型(text)",
           "mediumtext"=>           "中型字符型(mediumtext)",
           "longtext"=>             "大型字符型(longtext)",
           "tinyint"=>              "小数值型(tinyint)",
           "smallint"=>             "中数值型(smallint)",
           "int"=>                  "大数值型(int)",
           "bigint"=>               "超大数值型(bigint)",
           "float"=>                "数值浮点型(float)",
           "double"=>               "数值双精度型(double)",
           "date"=>                 "日期型(date)",
           "datetime"=>             "日期时间型(datetime)",
        );
        View::assign("fieldtype_inc",$this->fieldtype_inc);
        //表单类型
        $this->formtype_inc=array(
            "text"=>              "单行文本框(text)",
            "password"=>          "密码框(password)",
            "select"=>            "下拉框(select)",
            "selects"=>           "多选下拉(selects)",
            "radio"=>             "单选框(radio)",
            "checkbox"=>          "复选框(checkbox)",
            "textarea"=>          "多行文本框(textarea)",
            "tiny"=>              "推荐编辑器(tiny)",
            "editor"=>            "编辑器(editor)",
            "image"=>             "图片(image)",
            "morepic"=>           "多图上传(morepic)",
            "morevalue"=>         "多值字段(morevalue)",            
            "file"=>              "文件(file)",
            "video"=>             "视频(video)",
            "date"=>              "日期(date)",
            "baidumap"=>          "百度地图(map)",
        );  
        View::assign("formtype_inc",$this->formtype_inc);
        //快捷字段设置
        $this->normalfield_inc=array(
            ["field"=>"field","name"=>"文本框","fieldtype"=>"varchar","fieldlen"=>"255","formtype"=>"text","formwidth"=>"","formheight"=>"","defaultval"=>""],
            ["field"=>"field","name"=>"描述","fieldtype"=>"text","fieldlen"=>"","formtype"=>"textarea","formwidth"=>"100","formheight"=>"100","defaultval"=>""],
            ["field"=>"field","name"=>"图片","fieldtype"=>"varchar","fieldlen"=>"255","formtype"=>"image","formwidth"=>"","formheight"=>"","defaultval"=>""],    
            ["field"=>"field","name"=>"文件","fieldtype"=>"varchar","fieldlen"=>"255","formtype"=>"file","formwidth"=>"","formheight"=>"","defaultval"=>""],
            ["field"=>"field","name"=>"视频","fieldtype"=>"varchar","fieldlen"=>"255","formtype"=>"video","formwidth"=>"","formheight"=>"","defaultval"=>""],
            ["field"=>"field","name"=>"下拉","fieldtype"=>"varchar","fieldlen"=>"255","formtype"=>"select","formwidth"=>"","formheight"=>"","defaultval"=>"北京\r\n上海"],
            ["field"=>"field","name"=>"多选","fieldtype"=>"text","fieldlen"=>"","formtype"=>"checkbox","formwidth"=>"","formheight"=>"","defaultval"=>"北京\r\n上海"],
            ["field"=>"field","name"=>"单选","fieldtype"=>"varchar","fieldlen"=>"255","formtype"=>"radio","formwidth"=>"100","formheight"=>"","defaultval"=>"北京\r\n上海"],
            ["field"=>"field","name"=>"编辑器(tiny)","fieldtype"=>"longtext","fieldlen"=>"","formtype"=>"tiny","formwidth"=>"100","formheight"=>"500","defaultval"=>""],
            ["field"=>"field","name"=>"多图","fieldtype"=>"text","fieldlen"=>"","formtype"=>"morepic","formwidth"=>"","formheight"=>"","defaultval"=>""],
        );  
        View::assign("normalfield_inc",$this->normalfield_inc);
        //常用正则
        $this->pattern_inc=array(
            "/^[0-9.-]+$/"=>                             "数字",
            "/^[0-9-]+$/"=>                              "整数",
            "/^[1-9]\d*$/"=>                             "大于0",
            "/^[a-z]+$/i"=>                              "字母",
            "/^[0-9a-z]+$/i"=>                           "数字+字母",
            "/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/"=>          "E-mail",
            "/^[0-9]{5,20}$/"=>                          "QQ",
            "/^http:\/\//"=>                             "超级链接",
            "/^(1)[0-9]{10}$/"=>                         "手机号码",
            "/^[0-9-]{6,13}$/"=>                         "电话号码",
        );   
        View::assign("pattern_inc",$this->pattern_inc);
        //系统字段（禁止删除）
        $this->systemfield_inc=array("title","thumb","keywords","description","newstime","linkurl");
        View::assign("systemfield_inc",$this->systemfield_inc);
    }    
    public function index(){
        $table_id=Request::param("table_id");
        View::assign("table_id",$table_id);
        $data=$this->model->where("table_id",$table_id)->order('sort asc,field_id asc')->select();
        $tableName=Db::name("table")->where("table_id",$table_id)->value("table_name");
        View::assign("tableName",$tableName);
        View::assign("data",$data);
        return View::fetch();
    }
    //更新排序
    public function updateSort(){
        $field_id=Request::param('field_id');
        $sort=Request::param('sort');
        foreach($field_id as $key=>$v){
            $this->model->update(['field_id'=>$field_id[$key],'sort'=>$sort[$key]]);
        }
        $this->success("设置成功");
    }       
    public function add(){
        if(request()->isPost()){
            $data=$this->request->param();
            if(!$this->validate->check($data)){
                $this->error($this->validate->getError());
            }
            //完整表名获取 判断主表 还是副表
            $table_name = $this->model->getTbName($data['table_id'], $data['issystem']);  
            //验证字段在数据表里是否存在了
            if($this->model->field_exists($table_name,$data['field'])){
                $this->error("该字段在数据表已存在");
            }
            //查询这个字段在table_field是否存在，要排队table_id
            $where[]=["table_id","=",$data["table_id"]];
            $where[]=["field","=",$data["field"]];
            $HasTableField=Db::name("table_field")->where($where)->count();
            if($HasTableField){
                $this->error("字段已存在");
            }
            //增加字段
            $field = array(
                'tablename' => config('database.connections.mysql.prefix'). $table_name,
                'fieldname' => $data['field'],
                'fieldlen' => $data['fieldlen'],
                'defaultval' => $data['defaultval'],
            );  
            $this->model->addFieldSql($data['fieldtype'],$field);
            //更新htmlcode
            $TableModel=new \app\admin\model\TableModel();
            $data['htmlcode']=$TableModel->createFieldHtmlCode($data);
            $data['memberhtmlcode']=$TableModel->createMemberFieldHtmlCode($data);
            //如果是morevalue需要对defaultvalue进行加工
            if($data["formtype"]=="morevalue"){
                $data["defaultval"]=$this->model->detailMorevalueDefaultval($data);
            }   
            //
            $data['savefun_trigger']=implode("|",$data['savefun_trigger']);
            if($data['savefun_trigger']){
                $data['savefun_trigger']="|".$data['savefun_trigger']."|";
            }  
            $this->model->save($data);
            $lastId=$this->model->field_id;
            $this->UserLogModel->add(Request()->action(),$this->model->getName(),$lastId,$this->request->param());
            $this->success("添加成功");
        }else{
            $table_id=Request::param("table_id");
            View::assign("table_id",$table_id); 
            return View::fetch();
        }
    }
    public function update(){
        if(request()->isPost()){
            $data=$this->request->param();
            //增加field_id字段校验
            $this->validate->append('field_id','require');
            //
            if(!$this->validate->check($data)){
                $this->error($this->validate->getError());
            }
            //查询这个字段在table_field是否存在，要查当前table_id并table_id排除field_id
            $where[]=["table_id","=",$data["table_id"]];
            $where[]=["field","=",$data["field"]];         
            $where[]=["field_id","<>",$data["field_id"]];     
            $HasTableField=Db::name("table_field")->where($where)->count();
            if($HasTableField){
                $this->error("字段已存在");
            }
            //
            $r=$this->model->find($data['field_id']);
            //完整表名获取 判断主表 还是副表
            $table_name = $this->model->getTbName($r['table_id'],$r['issystem']);
            if ($data['field'] != $r['field']&& $this->model->field_exists($table_name, $data['field'])) {
                $this->error("该字段在数据表已存在");
            }
            $field = array(
                'tablename' => config('database.connections.mysql.prefix'). $table_name,
                'newfieldname' => $data['field'],
                'oldfieldname' => $r['field'],
                'fieldlen' => $data['fieldlen'],
                'defaultval' => $data['defaultval'],
            );            
            $this->model->editFieldSql($data['fieldtype'],$field);
            //更新htmlcode
            $TableModel=new \app\admin\model\TableModel();
            $data['htmlcode']= $data['htmlcode'] ?: $TableModel->createFieldHtmlCode($data);
            $data['memberhtmlcode']= $data['memberhtmlcode'] ?: $TableModel->createMemberFieldHtmlCode($data);
            //如果是morevalue需要对defaultvalue进行加工
            if($data["formtype"]=="morevalue"){
                $data["defaultval"]=$this->model->detailMorevalueDefaultval($data);
            }              
            //
            $data['savefun_trigger']=implode("|",$data['savefun_trigger']);
            if($data['savefun_trigger']){
                $data['savefun_trigger']="|".$data['savefun_trigger']."|";
            }               
            $this->model->update($data);
            //根据table_id查询model表，并更新modeltemp
            $model=Db::name("model")->where("table_id",$data["table_id"])->select();
            $ModelModel=new \app\admin\model\ModelModel();
            foreach($model as $v){
                $ModelModel->updateModelTemp($v);
                $ModelModel->updateModelTempMember($v);
            }            
            $this->UserLogModel->add(Request()->action(),$this->model->getName(),$r['field_id'],$this->request->param());
            $this->success("修改成功");
        }else{
            $field_id=Request::param("field_id");
            $r=$this->model->find($field_id);
            View::assign("r",$r);
            return View::fetch();
        }
    }
    //删除
    public function delete(){
        $field_id=Request::param('field_id',0,"intval");
        $r=$this->model->find($field_id);
        if(!$r){$this->error("数据不存在");}
        //完整表名获取 判断主表 还是副表
        $table_name = $this->model->getTbName($r['table_id'],$r['issystem']);
        //判断是否允许删除
        if (in_array($r['field'],$this->systemfield_inc)){
            $this->error("系统字段不允许被删除!");
        }
        $this->model->deleteFieldSql($r['field'], $table_name);
        $this->model->where("field_id",$field_id)->delete();
        //根据table_id查询model表，并更新modeltemp
        $model=Db::name("model")->where("table_id",$r['table_id'])->select();
        $ModelModel=new \app\admin\model\ModelModel();
        foreach($model as $v){
            $ModelModel->updateModelTemp($v);
        }   
        $this->UserLogModel->add(Request()->action(),$this->model->getName(),$field_id,$this->request->param());
        $this->success("删除成功");
    }
    //字段排序
    public function sort(){
        $filed_id=I("filed_id");
        $sort=I("sort");
        foreach($filed_id as $key=>$id){
            $data['field_id']=(int)$id;
            $data['sort']=(int)$sort[$key];
            $this->table->save($data);
        }     
        $this->success("排序更改成功");
    }
}